import numpy as np
from datetime import datetime
import time
import myfunc

def addNumTonp(area,num):
    """
    将num加入到area中  FIFO类型
    20200409注：python实现了标准fifo数据结构，此函数应废弃，性能很差。
    :param area: FIFO队列
    :param num: 要加入的num数组
    :return: 返回新的FIFO队列
    """
    numLen = len(num)
    numArea = len(area)
    temp = np.zeros(numArea-numLen)
    i = 0
    while i < numArea-numLen:
        temp[i] = area[i]
        i = i + 1
    i = 0
    while i < numLen:
        area[i] = num[i]
        i = i + 1
    i = 0
    while i < numArea-numLen:
        area[numLen+i] = temp[i]
        i = i + 1
    return area

def computerUserState(signalIn,windowsLen,fs):
    """
    根据能量段积分判断该段信号所对应的用户状态
    :param signalIn: 信号段  应为计算过逐差之后的信号
    :param windowsLen: 积分窗口的长度
    :param fs: 采样频率
    :return: 0-离床  1-稳定  2-微动  3-体动
    """
    signalIn1 = np.zeros(len(signalIn))
    i = 0
    while i < len(signalIn):
        signalIn1[i] = signalIn[i]*signalIn[i]
        i = i + 1
    windowsLen = 2 * fs
    signalLen = len(signalIn1)
    nengliang = np.zeros(len(signalIn1)) # 能量段的值  长度与signalIn相同
    i = 0
    while i < signalLen-windowsLen:
        nengliang[i] = np.sum(signalIn1[i:i+windowsLen])
        i = i + 1
    i = 0
    while i < windowsLen:
        nengliang[signalLen-windowsLen+i] = np.sum(signalIn1[signalLen-windowsLen:signalLen])
        i = i + 1
    i = 0
    while i < len(nengliang):
        if nengliang[i] < 0.1:
            nengliang[i] = 0
        elif nengliang[i] > 0.1 and nengliang[i] < 1.5:
            nengliang[i] = 1
        elif nengliang[i] > 1.5 and nengliang[i] < 10:
            nengliang[i] = 2
        else:
            nengliang[i] = 3
        i = i + 1
    return nengliang

def computerUserState2S(signalIn, windowsLen, fs):
    """
    计算两秒的能量值   返回一个数
    :param signalIn: 信号段
    :param windowsLen: 窗口长度
    :param fs: 采样率
    :return: 0-离床  1-稳定  2-微动  3-体动
    """

    signalIn1 = np.zeros(len(signalIn))
    i = 0
    while i < len(signalIn):
        signalIn1[i] = signalIn[i] * signalIn[i]
        i = i + 1
    nengliang = np.sum(signalIn1)
    print(nengliang)
    if nengliang < 100000000:
        nengliang = 0
    if nengliang >100000000 and nengliang < 500000000:
        nengliang = 1
    if nengliang > 500000000 and nengliang < 800000000:
        nengliang = 2
    if nengliang > 800000000:
        nengliang = 3
    return nengliang

def getBreathRate(signalIn,fs):
    """
    返回signalIn信号的平均呼吸率  单位（次/分钟）
    :param signalIn: 输入信号
    :param fs: 信号频率
    :return: 呼吸率
    """
    signalLen = len(signalIn)
    signalTime = signalLen/(fs*60)
    pingjunLine,pecks = myfunc.findBreathBeatsNew(signalIn,fs)
    pecksNum = len(pecks)
    return (pecksNum/signalTime)
